﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace PSE.AuditLogging.Common.Service
{
    public class ServiceHoster : IDisposable
    {
        private ServiceHost _host;
        private string _address;
        private Type _serviceInterface;
        private Type _serviceType;

        public ServiceHoster(string address, Type serviceInterface, Type serviceType)
        {
            _address = address;
            _serviceInterface = serviceInterface;
            _serviceType = serviceType;
        }

        public void Open()
        {
            _host = new ServiceHost(_serviceType, new Uri(_address));
            _host.AddServiceEndpoint(_serviceInterface, CreateNetPipeBinding(), "");
            _host.Open();
        }

        public void Close()
        {
            if (_host != null)
                _host.Close();
        }

        private Binding CreateNetPipeBinding()
        {
            NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
            binding.MaxBufferPoolSize = 122880;
            binding.MaxBufferSize = 2147483647;
            binding.MaxReceivedMessageSize = 2147483647;

            return binding;
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_host != null)
                _host.Close();
        }

        #endregion
    }
}
